import {
  Button,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Modal,
  Select,
  SelectOption,
  Space,
  TypographyText
} from 'ant-design-vue'
import form from 'ant-design-vue/lib/form'
import { fa } from 'element-plus/lib/locale'
import { values } from 'lodash-es'
import { computed, defineComponent, nextTick, onMounted, ref } from 'vue'
import { omit } from 'xe-utils'

import { marketingApi, riverApi } from '@/apis'
import { addHeadOfficeItem, editHeadOffice } from '@/apis/riverTypes'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useBack, useDialog } from '@/hooks'
import { provinceList } from '@/utils'
import { debounce } from '@/utils/throttle'

export default defineComponent({
  name: 'DivisionManage',
  setup() {
    const newMemberId = ref()
    const headOfficeId = ref()
    const showDialog = ref(false)
    const dialogLoading = ref(false)
    const pList = ref(provinceList)
    const nameList1 = ref([] as any[])
    const nameList2 = ref([] as any[])
    const nameList3 = ref([] as any[])
    const tempList = ref([] as any[])
    const tempList1 = ref([] as any[])
    const addCur = ref({} as addHeadOfficeItem)
    const optionItemCur = ref({} as editHeadOffice)
    // const { showConfirm } = useDialog()

    // const handleCancel = useBack('refreshFormationList')

    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          slots: {
            buttons: 'batchButtons'
          }
        },
        formConfig: {
          items: [
            {
              title: '总部名称',
              field: 'roleName',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 100
        },

        columns: [
          {
            title: '总部角色名称',
            field: 'roleName'
          },
          {
            title: '创建时间',
            field: 'createTime',
            Width: 100,
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss']
          },
          {
            title: '创建人',
            field: 'createUser',
            width: 100
          },
          {
            title: '下辖事业部',
            field: 'subordinateBusinessDivsionGroup'
          },
          {
            title: '总部负责人',
            field: 'headOfHeadQuarters',
            width: 100
          },
          {
            title: '手机号',
            field: 'phone',
            width: 150
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 150
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          seq: true,
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await riverApi.selectHeadOfficeInfoList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)
    //新增
    function add() {
      addCur.value = {} as addHeadOfficeItem
      nameList1.value = []
      nameList3.value = []
      showDialog.value = true
    }
    function selectId1(value) {
      newMemberId.value = value
    }
    //新增总部负责人查询
    function searchGroup(item) {
      debounce(async () => {
        try {
          const namelistarr = await riverApi.SearchHeadOfficeList({
            pageParameter: {
              pageSize: 15,
              currentPage: 1
            },
            principalName: item
          })
          nameList1.value = namelistarr.dataList
        } finally {
        }
      })
    }

    onMounted(() => {
      getGroupList()
    })
    // 新增下属事业部
    async function getGroupList() {
      try {
        nameList2.value = await riverApi.selectBusinessDivision({
          businessDivisionName: ''
        })
      } finally {
      }
    }

    function clear1() {
      newMemberId.value = null
    }

    //编辑总部查询
    async function edit(id) {
      debounce(async () => {
        try {
          optionItemCur.value = await riverApi.editHeadOfficeInfoList(
            id.headOfficeId
          )
          const editIdList =
            optionItemCur.value?.subordinateBusinessDivsionGroupId?.split(',')
          const editNameList =
            optionItemCur.value?.subordinateBusinessDivsionGroup?.split(',')
          const tempList = editIdList.map((k, index) => {
            return {
              headOfficeId: k,
              businessDivisionName: editNameList[index]
            }
          })
          tempList.value = [
            {
              headOfficeId: 'k',
              businessDivisionName: 'editNameList[index]'
            }
          ]
          nameList3.value = [...tempList]
          addCur.value.headOfficeId = id.headOfficeId

          addCur.value.subordinateBusinessDivisionIdList =
            optionItemCur.value.subordinateBusinessDivsionGroupId
              .split(',')
              .map(item => Number(item))

          addCur.value.roleName = optionItemCur.value.roleName

          addCur.value.headOfHeadQuarters =
            optionItemCur.value.headOfHeadQuarters
          addCur.value.newMemberId = optionItemCur.value.memberId
          addCur.value.memberId = optionItemCur.value.memberId
          nameList1.value = [
            {
              newMemberId: optionItemCur.value.memberId,
              headOfHeadQuarters: optionItemCur.value.headOfHeadQuarters
            }
          ]
        } finally {
        }
      })
      showDialog.value = true
    }

    //编辑/新增确定
    async function dialogConfirm() {
      if (!addCur.value.roleName) {
        message.error('请输入总部角色名称')
        return
      }
      if (!addCur.value.newMemberId) {
        message.error('请输入总部负责人')
        return
      }
      if (
        !addCur.value.subordinateBusinessDivisionIdList ||
        addCur.value.subordinateBusinessDivisionIdList == 0
      ) {
        message.error('请输入下辖事业部')
        return
      }

      try {
        dialogLoading.value = true
        if (addCur.value.headOfficeId) {
          await riverApi.editHeadOfficeList(addCur.value)
        } else {
          await riverApi.addHeadOfficeList(addCur.value)
        }
        showDialog.value = false
        getGroupList()
        tableRef.value.refresh()
      } finally {
        dialogLoading.value = false
      }
    }
    function showGroup() {
      if (addCur.value.headOfficeId) {
        return '编辑'
      } else {
        return '新增'
      }
    }
    return {
      tableRef,
      nameList1,
      nameList2,
      nameList3,
      tempList,
      tempList1,
      tableConfig,
      optionItemCur,
      newMemberId,
      showDialog,
      addCur,
      dialogLoading,
      pList,
      showGroup,
      getGroupList,
      searchGroup,
      selectId1,
      dialogConfirm,
      clear1,
      add,
      edit
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            batchButtons: () => (
              <Space>
                <Button type="primary" onClick={() => this.add()}>
                  新增
                </Button>
              </Space>
            ),

            operation: ({ row }) => (
              <Space>
                <Button type="link" size="small" onClick={() => this.edit(row)}>
                  编辑
                </Button>
              </Space>
            )
          }}
          {...this.tableConfig}
        />
        <Modal
          v-model:visible={this.showDialog}
          confirmLoading={this.dialogLoading}
          title={this.showGroup}
          destroyOnClose
          onOk={this.dialogConfirm}
        >
          <Form labelCol={{ span: 6 }}>
            <FormItem label={'总部角色名称'} required>
              <Input
                maxlength={60}
                v-model:value={this.addCur.roleName}
                placeholder="请输入"
                style={{ width: '200px' }}
              />
            </FormItem>
            <FormItem label="总部负责人" required>
              <Select
                filterOption={false}
                showSearch={true}
                onClear={this.clear1}
                option-label-prop="label"
                dropdownMatchSelectWidth={false}
                onSearch={num => this.searchGroup(num)}
                placeholder="请输入"
                style="width: 200px"
                v-model:value={this.addCur.newMemberId}
                onChange={this.selectId1}
                allowClear
              >
                {this.nameList1.map(v => (
                  <SelectOption
                    value={v.newMemberId}
                    label={v.headOfHeadQuarters}
                  >
                    {`${v.headOfHeadQuarters ? v.headOfHeadQuarters : '暂无'}
                      ${v.phone || ''}`}
                  </SelectOption>
                ))}
              </Select>
            </FormItem>
            <FormItem label={'下辖事业部'} required>
              <Select
                mode="multiple"
                placeholder="请选择"
                style={{ width: '200px' }}
                option-label-prop="label"
                v-model:value={this.addCur.subordinateBusinessDivisionIdList}
              >
                {this.nameList2.map(v => (
                  <SelectOption
                    value={v.headOfficeId}
                    label={v.businessDivisionName}
                  >
                    {`${v.businessDivisionName || ''}`}
                  </SelectOption>
                ))}
                {/* {this.nameList3.map(k => (
                  <SelectOption
                    value={k.headOfficeId}
                    label={k.businessDivisionName}
                  >
                    {`${k.businessDivisionName || ''}`}
                  </SelectOption>
                ))} */}
              </Select>
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
})
